package com.softtek.ibeacon.web.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.softtek.ibeacon.common.ServiceException;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class MV extends ModelAndView {
	static String realPath = "/webapps";
	static String ctxpath = "/";
	static String custId = "";
	static String viewFolderName = "view";
	static String extViewFolderName = "page";

	private String viewName;
	private Object modelObject;
	private String command;
	private Object actionObj;
	private static final Log logger = LogFactory.getLog(MV.class);

	public MV() {
		super();
	}

	public MV(String viewName) {
		super(getPath(viewName, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()));
		this.viewName = viewName;

	}

	public MV(String viewName, Object actionObj) {
		super(getPath(viewName, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()));
		this.actionObj = actionObj;
		this.viewName = viewName;
	}

	public MV(String viewName, Map modelObject) {
		super(getPath(viewName, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()), modelObject);
		this.viewName = viewName;
		this.modelObject = modelObject;

	}

	public MV(String viewName, String modelName, Object modelObject) {
		super(getPath(viewName, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()), modelName, modelObject);
		this.viewName = viewName;
		this.modelObject = modelObject;
		this.command = modelName;
	}

	public MV(String viewName, String modelName, Object modelObject, Object actionObj) {
		super(getPath(viewName, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()), modelName, modelObject);
		this.viewName = viewName;
		this.modelObject = modelObject;
		this.command = modelName;
		this.actionObj = actionObj;
	}

	/**
	 * 将url转换为带view或者page目录
	 */
	public static String getPath(String url, HttpServletRequest req) {
		if (url.startsWith("redirect:")) {
			return url;
		}

		return url;
	}

	/**
	 * 
	 * @param e
	 *            原始异常
	 * @param errorInfo
	 *            自定义错误提示信息，可以直接传中文信息，也可以传I18N key
	 * @return
	 */
	public ModelAndView processException(Exception e, String errorInfo) {
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String url = req.getRequestURI();
		if (url.endsWith(".do")) {
			// if (e instanceof DataAccessException) {
			try {
				HttpServletResponse res = ActionUtil.getCtx().getResponse();
				/*
				 * res.setCharacterEncoding("utf-8");
				 * res.setContentType("text/html;charset=UTF-8"); PrintWriter
				 * out = res.getWriter(); Map m = new HashMap();
				 * m.put("status","500");
				 * m.put("msg",StringUtils.isNotBlank(errorInfo) ? errorInfo :
				 * "操作出错!"); out.println(JSONObject.fromObject(m).toString());
				 */
				logger.error("error", e);
				this.setViewName("/com/error/error");
				return this;
			} catch (Exception e2) {
				logger.error("error", e2);
			}
		} else if (url.endsWith(".pdfx")) {
			return null;
		} else if (url.endsWith(".xlsx")) {

			return null;
		} else {
			logger.error("error", e);
			try {
				HttpServletResponse res = ActionUtil.getCtx().getResponse();
				res.setContentType("text/html;charset=UTF-8");
				PrintWriter out = res.getWriter();
				Map m = new HashMap();
				m.put("status", "500");
				if(e instanceof ServiceException){
					m.put("msg", e.getMessage());
				} else { 
					m.put("msg", StringUtils.isNotBlank(errorInfo) ? errorInfo : "出错了!"); 
				}
				Gson gson=new Gson();
				out.println(gson.toJson(m).toString());
				out.close();

			} catch (IOException ex) {
				logger.error("error", ex);
			}
		}
		return null;
	}

	
	
	public ModelAndView fwd() {
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		String url = req.getRequestURI();

		if (url.endsWith(".do")) {
			return this;
		} else if (url.endsWith(".pdfx")) {

		} else if (url.endsWith(".xlsx")) {

		} else {
			Map m = this.getModelMap();
			
			HttpServletResponse res = ActionUtil.getCtx().getResponse();
			res.setContentType("text/html;charset=UTF-8");
			try {
				PrintWriter out = res.getWriter();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.sql.Date.class, new com.softtek.ibeacon.web.util.JsonDateValueProcessor());
				cfg.registerJsonValueProcessor(java.util.Date.class, new com.softtek.ibeacon.web.util.JsonDateValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Timestamp.class, new com.softtek.ibeacon.web.util.JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
				if (m.get("status") == null) {
					m.put("status", "1");
				}else{
					m.put("status", "0");
				}
				out.println(JSONObject.fromObject(m, cfg).toString());
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
				PrintWriter out;
				try {
					out = res.getWriter();
					if (m.get("status") == null) {
						m.put("status", "500");
						m.put("msg", "出错了!");
					}
					out.println(JSONObject.fromObject(m).toString());
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			return null;
		}
		return null;
	}

	
	
 
}
